import 'package:azring/core/controllers/ring_controller.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/services/ring_service.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_record_state.dart';

/// 运动记录详情控制器
class ExerciseRecordDetailLogic extends GetxController {
  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  // 获取戒指服务
  RingService get ringService => Get.find<RingService>();

  // 当前记录
  late HistoryTrainingRecord record;

  // 是否正在加载详情
  final isLoadingDetail = false.obs;

  // 是否正在上报数据
  final isReporting = false.obs;

  // 锻炼详情数据
  final Rx<Map<String, dynamic>?> exerciseDetail =
      Rx<Map<String, dynamic>?>(null);

  @override
  void onInit() {
    super.onInit();

    // 从路由参数获取记录
    record = Get.arguments as HistoryTrainingRecord;

    // 查询锻炼详情
    queryExerciseDetailFromDevice();
  }

  /// 从设备查询锻炼详情
  void queryExerciseDetailFromDevice() async {
    try {
      isLoadingDetail.value = true;

      print(
          '📊 开始查询设备锻炼详情: trainingId=${record.trainingId}, rawTime=${record.rawTime}');

      // 监听锻炼详情数据变化
      _listenToExerciseDetailChanges();

      // 从历史训练列表中找到当前记录的索引
      final historyList = ringService.historyTrainingListRx;
      int? recordIndex;

      for (int i = 0; i < historyList.length; i++) {
        final item = historyList[i];
        final rawData = item['rawData'] as String? ?? '';
        final rawTimeMatch = RegExp(r'rawTime=(\d+)').firstMatch(rawData);

        if (rawTimeMatch != null) {
          final rawTime = int.parse(rawTimeMatch.group(1)!);
          if (rawTime == record.rawTime) {
            recordIndex = i;
            break;
          }
        }
      }

      if (recordIndex == null) {
        print('❌ 未在历史列表中找到当前记录');
        Toast.show('未找到训练记录');
        return;
      }

      print('✅ 找到记录索引: $recordIndex');

      // 调用 SDK 根据索引查询训练详情
      final success = await ringService.queryTrainingByIndex(recordIndex);

      if (success) {
        print('✅ 查询锻炼详情请求已发送，等待 SDK 回调');
        // 不在这里关闭 loading，等待数据返回后再关闭
      } else {
        print('❌ 查询锻炼详情请求失败');
        Toast.show('查询锻炼详情失败');
        isLoadingDetail.value = false;
      }
    } catch (e) {
      print('❌ 查询锻炼详情异常: $e');
      Toast.show('查询锻炼详情异常');
      isLoadingDetail.value = false;
    }
  }

  /// 监听锻炼详情数据变化
  void _listenToExerciseDetailChanges() {
    // 监听 RingService 中的锻炼详情数据
    ever(ringService.exerciseDetailRx, (detail) {
      if (detail != null) {
        print('📊 收到锻炼详情数据变化: $detail');

        // 数据格式可能是 {rawData: CRPTrainingInfo{...}} 或 {rawInfo: CRPTrainingInfo{...}}
        final rawData =
            detail['rawData'] as String? ?? detail['rawInfo'] as String? ?? '';
        final rawStartTimeMatch =
            RegExp(r'rawStartTime=(\d+)').firstMatch(rawData);

        if (rawStartTimeMatch != null) {
          final rawStartTime = int.parse(rawStartTimeMatch.group(1)!);

          // 匹配当前记录
          if (rawStartTime == record.rawTime) {
            print('✅ 匹配到当前记录的锻炼详情');
            exerciseDetail.value = detail;

            // 关闭 loading
            isLoadingDetail.value = false;

            // 自动上报锻炼详情到服务器
            reportExerciseDetail();
          } else {
            print(
                '⚠️ 收到的锻炼详情不匹配当前记录: rawStartTime=$rawStartTime, record.rawTime=${record.rawTime}');
          }
        } else {
          print('⚠️ 无法从数据中提取 rawStartTime: $rawData');
        }
      }
    });
  }

  /// 上报锻炼详情到服务器
  Future<void> reportExerciseDetail() async {
    try {
      isReporting.value = true;

      // 获取设备序列号
      final deviceSn = ringController.getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        print('❌ 设备未连接，无法上报锻炼详情');
        return;
      }

      // 从 exerciseDetail 中提取数据
      final detail = exerciseDetail.value;
      if (detail == null) {
        print('❌ 锻炼详情数据为空');
        return;
      }

      // 解析 rawInfo 或 rawData 字符串
      final rawInfo =
          detail['rawInfo'] as String? ?? detail['rawData'] as String? ?? '';
      final parsedData = _parseRawInfo(rawInfo);

      if (parsedData == null) {
        print('❌ 解析 rawInfo/rawData 失败');
        return;
      }

      // 提取 exerciseType
      final typeMatch = RegExp(r'type=(\d+)').firstMatch(rawInfo);
      final exerciseType = typeMatch != null
          ? int.parse(typeMatch.group(1)!)
          : record.trainingType;

      print('📤 开始上报锻炼详情: deviceSn=$deviceSn');
      print('   exerciseType=$exerciseType');
      print('   startTime=${parsedData['startTime']}');
      print('   endTime=${parsedData['endTime']}');
      print('   validTime=${parsedData['validTime']}');
      print('   calories=${parsedData['calories']}');
      print('   hrList length=${parsedData['hrList']?.length ?? 0}');

      // 生成 recordDate（当前日期）
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      // 调用 API 上报
      final result = await DefaultApi().addExerciseDetailPost<dynamic>(
        deviceSn: deviceSn,
        rawStartTime: parsedData['startTime'],
        exerciseType: exerciseType.toString(),
        startTime: parsedData['startTime'],
        endTime: parsedData['endTime'],
        hrList: parsedData['hrList'],
        steps: parsedData['steps']?.toString(),
        distance: parsedData['distance']?.toString(),
        calories: parsedData['calories']?.toString(),
        validTime: parsedData['validTime']?.toString(),
        goalType: parsedData['goalType']?.toString(),
        goalValue: parsedData['goalValue']?.toString(),
        recordDate: recordDate,
        isShowErrMsg: true,
        isShowLoading: true,
      );

      if (result != null) {
        print('✅ 锻炼详情上报成功');
      } else {
        print('❌ 锻炼详情上报失败');
      }
    } catch (e) {
      print('❌ 上报锻炼详情异常: $e');
    } finally {
      isReporting.value = false;
    }
  }

  /// 解析 rawInfo 字符串
  /// 格式: CRPTrainingInfo{type=23, rawStartTime=1755332255000, startTime=1755332255000, endTime=1755333591000, validTime=1333, steps=0, distance=0, calories=13, goalType=255, goalValue=0, hrList=[...]}
  Map<String, dynamic>? _parseRawInfo(String rawInfo) {
    try {
      final result = <String, dynamic>{};

      // 提取各个字段
      final startTimeMatch = RegExp(r'startTime=(\d+)').firstMatch(rawInfo);
      final endTimeMatch = RegExp(r'endTime=(\d+)').firstMatch(rawInfo);
      final validTimeMatch = RegExp(r'validTime=(\d+)').firstMatch(rawInfo);
      final stepsMatch = RegExp(r'steps=(\d+)').firstMatch(rawInfo);
      final distanceMatch = RegExp(r'distance=(\d+)').firstMatch(rawInfo);
      final caloriesMatch = RegExp(r'calories=(\d+)').firstMatch(rawInfo);
      final goalTypeMatch = RegExp(r'goalType=(\d+)').firstMatch(rawInfo);
      final goalValueMatch = RegExp(r'goalValue=(\d+)').firstMatch(rawInfo);

      // 提取心率列表
      final hrListMatch = RegExp(r'hrList=\[([\d,\s]+)\]').firstMatch(rawInfo);

      if (startTimeMatch != null) {
        final startTimeMs = int.parse(startTimeMatch.group(1)!);
        result['startTime'] = DateTime.fromMillisecondsSinceEpoch(startTimeMs)
            .toIso8601String()
            .replaceAll('T', ' ')
            .substring(0, 19);
      }

      if (endTimeMatch != null) {
        final endTimeMs = int.parse(endTimeMatch.group(1)!);
        result['endTime'] = DateTime.fromMillisecondsSinceEpoch(endTimeMs)
            .toIso8601String()
            .replaceAll('T', ' ')
            .substring(0, 19);
      }

      if (validTimeMatch != null) {
        result['validTime'] = int.parse(validTimeMatch.group(1)!);
      }

      if (stepsMatch != null) {
        result['steps'] = int.parse(stepsMatch.group(1)!);
      }

      if (distanceMatch != null) {
        result['distance'] = int.parse(distanceMatch.group(1)!);
      }

      if (caloriesMatch != null) {
        result['calories'] = int.parse(caloriesMatch.group(1)!);
      }

      if (goalTypeMatch != null) {
        result['goalType'] = int.parse(goalTypeMatch.group(1)!);
      }

      if (goalValueMatch != null) {
        result['goalValue'] = int.parse(goalValueMatch.group(1)!);
      }

      if (hrListMatch != null) {
        final hrListStr = hrListMatch.group(1)!;
        final hrList = hrListStr
            .split(',')
            .map((s) => int.tryParse(s.trim()))
            .where((v) => v != null)
            .toList();
        result['hrList'] = hrList;
      }

      return result;
    } catch (e) {
      print('❌ 解析 rawInfo 异常: $e');
      return null;
    }
  }

  /// 更新锻炼详情数据（由 RingService 调用）
  void updateExerciseDetail(Map<String, dynamic> detail) {
    exerciseDetail.value = detail;
    print('✅ 锻炼详情数据已更新');

    // 自动上报
    reportExerciseDetail();
  }
}
